﻿
//关闭当前页 返回父页面
function closePage(isReload) {
    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    parent.layer.close(index); //再执行关闭
    if (isReload) {
        parent.search();
    }
}

layui.use(['form', 'layer', 'laydate', 'upload'], function () {
    var form = layui.form,
        layer = layui.layer,
        laydate = layui.laydate,
        upload = layui.upload;

    laydate.render({
        elem: '#tbBeginDate',
        type: 'date',
        trigger: 'click'
    });

    laydate.render({
        elem: '#tbEndDate',
        type: 'date',
        trigger: 'click'
    });

    var personImageUrl = '/Business/Common/UploadifyHandler.ashx?PostType=upload&RecordType=PersonPicturesTemp';

    //上传身份证头像
    var uploadPersonPhoto = upload.render({
        elem: '#tbHideUploadImageUrl'
        , url: personImageUrl
        , data: {
            IDCard: $('#tbIDCard').val()
        }
        , accept: 'images'
        , acceptMime: 'image/*'
        , exts: 'jpg'
        //, size: 50
        , before: function (obj) {
            layer.load(); //上传loading
        }
        , done: function (res, index) {
            layer.closeAll('loading');
            if (res.AnnexPath) {
                $('#tbImageUrl').val(res.AnnexPath);
                $('#jpgfile').attr('src', res.AnnexPath + '?rnd=' + Math.random());
            }
        }
        , error: function (index, upload) {
            layer.closeAll('loading');
        }
    });

    //重载上传按钮
    window.uploadImageUrl = function () {
        var idCard = $('#tbIDCard').val();
        if (!idCard) {
            layer.msg('请输入身份证号！');
            return;
        }
        if (!isCardID(idCard)) {
            layer.msg('身份证号不正确！');
            return;
        }

        uploadPersonPhoto.reload({
            url: personImageUrl + "&IDCard=" + idCard
        });
        $('#tbHideUploadImageUrl').click();
    }

    $(function () {
        if (app.getRequest('GUID')) {
            initData();
        }
    });

    //初始化表单
    function initData() {
        var fieldData = {
            GUID: app.getRequest('GUID'),
            PostType: "get",
            ActionType: "Person"
        };
        app.loadData("Person.ashx", fieldData, function (data) {
            if (data.PersonSex == "男") {
                $('#rdPersonSex1').prop("checked", true);
            } else {
                $('#rdPersonSex2').prop("checked", true);
            }
            if (data.BeginDate) {
                $('#tbBeginDate').val(app.getTDate2(data.BeginDate));
            }
            if (data.EndDate) {
                $('#tbEndDate').val(app.getTDate2(data.EndDate));
            }

            if (data.ImageUrl) {
                $("#jpgfile").attr('src', data.ImageUrl + '?t=' + Math.random());
            }

            form.render();
        }, function (err) {
            layer.msg('请求失败');
        });
    }

    //保存
    form.on('submit(save)', function (data) {
        //if (!$('#tbImageUrl').val()) {
        //    layer.msg('请上传身份证头像！');
        //    return false;
        //}

        var fieldData = data.field;
        fieldData["GUID"] = app.getRequest('GUID');
        fieldData["ActionType"] = "Person";
        app.set("Person.ashx", fieldData, function (data) {
            layer.msg(data.msg);
            if (data.success) {
                setTimeout(function () {
                    closePage(true);
                }, 1000);
            }
        }, function (err) {
            layer.msg('请求失败');
        });
        return false;
    });
});

//初始化读卡器-卡尔
function initIDCard() {
    getRFReaderInfo();
}

//KT80读取设备信息
var baseUrl = "http://127.0.0.1:6045";
function getRFReaderInfo() {
    var start = new Date();
    var param = { "portType": 5 };
    $.ajax({
        contentType: "application/json;charset=UTF-8",
        dataType: 'jsonp',
        timeout: 10000,
        jsonp: "callback",
        url: baseUrl + "/getReaderInfo?param=" + JSON.stringify(param),
        success: function (data, status) {
            //successCallback && successCallback(resultInfo);
            if (data.result == 0) {
                var readerVersion = data.readerVersion;
                if (readerVersion) {
                    getRFIdCardRead();
                } else {
                    alert('未能获取到设备信息');
                }
            } else {
                if (data.errorMsg.indexOf("未定义错误") > -1) {
                    getRFReaderInfo();
                } else {
                    alert(data.errorMsg + ' 请重试');
                }
            }
        },
        complete: function (XMLHttpRequest, textStatus) {

        },
        error: function (jqXHR, textStatus, errorThrown) {
            //console.error("getReaderInfo recv text " + textStatus + " errorThrown " + errorThrown);
            //errorCallback && errorCallback();
            alert('获取设备信息失败，请联系平台管理人员！');
        }
    });
}

//RF读取
function getRFIdCardRead() {
    var param = { "portType": 5 };
    $.ajax({
        contentType: "application/json;charset=UTF-8",
        dataType: 'jsonp',
        timeout: 10000,
        jsonp: "callback",
        url: baseUrl + "/readIDCard?param=" + JSON.stringify(param),
        success: function (resultInfo, status) {
            if (resultInfo.result === 0) {
                //console.info("read card success");

                var textInfo = resultInfo.wzInfo;
                $("#tbPersonName").val(textInfo.substr(0, 15).trim());
                var personSex = textInfo.substr(15, 1).trim() == 1 ? '男' : '女';
                $("#tbPersonSex").val(personSex);
                if (personSex == "男") {
                    $('#rdPersonSex1').prop("checked", true);
                } else {
                    $('#rdPersonSex2').prop("checked", true);
                }
                $("#tbBorn").val(textInfo.substr(18, 8).trim());
                $("#tbAddress").val(textInfo.substr(26, 35).trim());
                $("#tbIDCard").val(textInfo.substr(61, 18).trim());
                $("#tbOrganize").val(textInfo.substr(79, 15).trim());

                //$("#tbPersonNation").val(textInfo.substr(16, 2).trim());
                var nation = textInfo.substr(16, 2).trim();
                $.get("/Business/Common/Common.ashx?PostType=get&ActionType=Nation&NationCode=" + nation, function (result) {
                    $("#tbPersonNation").val(result);
                });

                //$("#text_beginterm").val(textInfo.substr(94, 8).trim());
                //$("#text_endterm").val(textInfo.substr(102, 8).trim());
                var start = textInfo.substr(94, 8).trim();
                var s1 = start.toString().substr(0, 4);
                var s2 = start.toString().substr(4, 2);
                var s3 = start.toString().substr(6, 2);
                start = s1 + '-' + s2 + '-' + s3;
                var end = textInfo.substr(102, 8).trim();
                var Str;
                if (end.indexOf("长期") > -1) {
                    end = '9999.12.31';
                } else {
                    var e1 = end.toString().substr(0, 4);
                    var e2 = end.toString().substr(4, 2);
                    var e3 = end.toString().substr(6, 2);
                    end = e1 + '-' + e2 + '-' + e3;
                }
                Str = start + "-" + end;
                $('#tbBeginDate').val(start);
                $('#tbEndDate').val(end);

                var end = new Date();
                $.ajax({
                    contentType: "application/json;charset=UTF-8",
                    dataType: 'jsonp',
                    jsonp: "callback",
                    url: baseUrl + "/wltUnpack?wlt=" + resultInfo.zpWlt + "&format=JPG",
                    success: function (response) {
                        if (response['result'] === 0) {
                            var imageBase64 = response['image'];
                            $("#text_photobase64").val(imageBase64);
                            var base64Str = 'data:image/jpeg;base64,' + imageBase64;
                            $('#tbImageUrl').val(base64Str);
                            $('#jpgfile').attr('src', base64Str);
                        } else {
                            alert("解析头像失败：" + response['result']);
                        }
                    },
                    complete: function (XMLHttpRequest, textStatus) {
                    },
                    error: function (jqXHR, textStatus, errorThrown) {

                    }
                });

                layui.form.render();
            } else {
                alert(resultInfo.errorMsg);
            }
        },
        complete: function (XMLHttpRequest, textStatus) {
            //alert("cloudReadCard/appId complete");
        },
        error: function (jqXHR, textStatus, errorThrown) {
            //console.error("read card error recv text "+ textStatus+" errorThrown "  +errorThrown );
        }
    });
}
